import { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Upload, Avatar, message, Spin, Descriptions } from 'antd';
import { UserOutlined, UploadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useAuthStore } from '@/stores/useAuthStore';
import { getCurrentUser, updateCurrentUser, changePassword } from '@/api/auth';
import { uploadFile } from '@/pages/File/api';
import styles from './index.module.css';

const Profile = () => {
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const { user, setUser, fetchUserInfo } = useAuthStore();

  // 加载用户信息
  useEffect(() => {
    loadUserInfo();
  }, []);

  const loadUserInfo = async () => {
    try {
      setLoading(true);
      const response = await getCurrentUser();
      if (response.data.success) {
        const userData = response.data.data;
        setUser(userData);
        form.setFieldsValue({
          email: userData.email,
          firstName: userData.firstName || '',
          lastName: userData.lastName || '',
        });
        setAvatarUrl(userData.avatar || '');
      }
    } catch (error) {
      message.error('加载用户信息失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理头像上传
  const handleAvatarUpload = async (file: File) => {
    // 检查文件大小（30MB限制）
    const maxSize = 30 * 1024 * 1024; // 30MB
    if (file.size > maxSize) {
      message.error('文件大小不能超过30MB');
      return false;
    }

    // 检查文件类型
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件');
      return false;
    }

    try {
      setUploading(true);
      const response = await uploadFile(file);
      
      if (response.data.success) {
        const fileData = response.data.data;
        const newAvatarUrl = fileData.url || '';
        
        // 更新用户头像
        await updateCurrentUser({ avatar: newAvatarUrl });
        
        // 刷新用户信息
        const userResponse = await getCurrentUser();
        if (userResponse.data.success) {
          const userData = userResponse.data.data;
          setUser(userData);
          setAvatarUrl(userData.avatar || '');
        }
        
        message.success('头像上传成功');
      }
    } catch (error: any) {
      message.error(error.response?.data?.message || '头像上传失败');
    } finally {
      setUploading(false);
    }
    return false; // 阻止默认上传行为
  };

  // 保存基本信息
  const handleSaveProfile = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const response = await updateCurrentUser(values);
      if (response.data.success) {
        await fetchUserInfo();
        message.success('个人信息更新成功');
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.error('请检查表单信息');
      } else {
        message.error('更新失败');
      }
    } finally {
      setLoading(false);
    }
  };

  // 修改密码
  const handleChangePassword = async () => {
    try {
      const values = await passwordForm.validateFields();
      setLoading(true);
      const response = await changePassword(values.oldPassword, values.newPassword);
      if (response.data.success) {
        message.success('密码修改成功');
        passwordForm.resetFields();
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.error('请检查表单信息');
      } else {
        message.error(error.response?.data?.message || '密码修改失败');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.profileContainer}>
      <Spin spinning={loading}>
        {/* 基本信息 */}
        <Card title="基本信息" className={styles.card}>
          <Form form={form} layout="vertical" className={styles.form}>
            <Form.Item label="头像">
              <div className={styles.avatarSection}>
                <Avatar 
                  size={80} 
                  icon={<UserOutlined />} 
                  src={avatarUrl} 
                  className={styles.avatar}
                />
                <Upload accept="image/*" showUploadList={false} beforeUpload={handleAvatarUpload} maxCount={1}>
                  <Button icon={<UploadOutlined />} loading={uploading}>
                    上传头像
                  </Button>
                </Upload>
                <p className={styles.avatarTip}>支持 JPG、PNG、GIF 格式，建议尺寸 200x200，文件不超过30MB</p>
              </div>
            </Form.Item>

            <Form.Item label="邮箱" name="email">
              <Input disabled />
            </Form.Item>

            <Form.Item label="名字" name="firstName" rules={[{ max: 100, message: '名字最多100个字符' }]}>
              <Input placeholder="请输入名字" />
            </Form.Item>

            <Form.Item label="姓氏" name="lastName" rules={[{ max: 100, message: '姓氏最多100个字符' }]}>
              <Input placeholder="请输入姓氏" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" onClick={handleSaveProfile}>
                保存信息
              </Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 账户信息 */}
        {user && (
          <Card title="账户信息" className={styles.card}>
            <Descriptions column={2} bordered>
              <Descriptions.Item label="用户ID">{user.id}</Descriptions.Item>
              <Descriptions.Item label="角色">{(user as any).role?.name || '普通用户'}</Descriptions.Item>
              <Descriptions.Item label="注册时间">
                {user.createdAt ? dayjs(user.createdAt).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="最后更新">
                {user.updatedAt ? dayjs(user.updatedAt).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        )}

        {/* 修改密码 */}
        <Card title="修改密码" className={styles.card}>
          <Form form={passwordForm} layout="vertical" className={styles.form}>
            <Form.Item label="旧密码" name="oldPassword" rules={[{ required: true, message: '请输入旧密码' }]}>
              <Input.Password placeholder="请输入旧密码" />
            </Form.Item>

            <Form.Item
              label="新密码"
              name="newPassword"
              rules={[
                { required: true, message: '请输入新密码' },
                { min: 8, message: '密码至少8个字符' },
                {
                  pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]/,
                  message: '密码必须包含大小写字母、数字和特殊字符',
                },
              ]}
              extra="密码要求：至少8个字符，包含大小写字母、数字和特殊字符"
            >
              <Input.Password placeholder="请输入新密码" />
            </Form.Item>

            <Form.Item
              label="确认新密码"
              name="confirmPassword"
              dependencies={['newPassword']}
              rules={[
                { required: true, message: '请确认新密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请确认新密码" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" onClick={handleChangePassword}>
                修改密码
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Spin>
    </div>
  );
};

export default Profile;

